from django import  forms
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View


class MyFrom(forms.Form):
    username = forms.CharField(min_length=3,max_length=8,label='用户名',error_messages={
        'min_length': '用户名最少为3位',
        'max_length': '用户名最大为8位',
        'required': '用户名不能为空'
    })

    password = forms.CharField(min_length=3, label='密码',error_messages={
        'min_length': '密码最少为3位',
        'required': '密码不能为空'

    },widget=forms.widgets.PasswordInput())

    qrpassword = forms.CharField(min_length=3, label='确认密码',error_messages={
        'min_length': '密码最少为3位',
        'required': '密码不能为空'

    },widget=forms.widgets.PasswordInput())
    email = forms.EmailField(label='邮箱',error_messages={
        'required': '邮箱不能为空',
        'invalid': '邮箱格式不正确',
    })


    # gender = forms.ChoiceField(choices=((1,'男'),(2,'女'),(3,'保密')),label='性别')
# #多选
    hobby =forms.MultipleChoiceField(choices=((1,'听歌'),(2,'玩游戏')),label='兴趣爱好',
                                     widget=forms.widgets.CheckboxSelectMultiple())

    # 钩子函数（自定义验证）:局部钩子和全局钩子  （自动调用 钩子函数命名方法 ：clean_属性名）
    # 局部钩子
    def clean_username(self):
        username = self.cleaned_data.get('username')
        if '顾轩顾轩' in username:
            self.add_error('username','你输入的用户名已经存在！')
        return username

    def clean(self):
        password = self.cleaned_data.get('password')
        qrpassword = self.cleaned_data.get('qrpassword')

        if password != qrpassword:
            # add_error 格式 (属性名，报错信息)
            self.add_error('qrpassword','密码不一致，请重新输入！')


    # PasswordInput()密码框
    # TextInput() 文本框
    # RadioSelect()单选框
    # CheckboxSelectMultiple()多选框
    # Select()下拉框


class FormsIndex(View):
    def get(self,request):
        myform_obj = MyFrom()
        return render(request,'drf21_09/form_obj.html',{"myform_obj":myform_obj})

    def post(self, request):
        # 获取用户数据进行校验
        myform_obj = MyFrom(request.POST)
        # 判断数据是否合法
        if myform_obj.is_valid():
            print('3242532')
            return HttpResponse('注册成功')

        # 如果数据不合法则把错误信息显示在前端

        return render(request, 'drf21_09/form_obj.html', {'myform_obj': myform_obj})

